package org.xserver.component.core.dispatch.http;

import java.io.RandomAccessFile;

import javax.activation.MimetypesFileTypeMap;

import org.jboss.netty.channel.DefaultFileRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xserver.component.annotation.Config;
import org.xserver.component.core.XServerHttpContextAttachment;
import org.xserver.component.core.XServerHttpResponse;
import org.xserver.component.core.http.HttpEnum;
import org.xserver.component.handler.ext.WriteHandler;
import org.xserver.component.handler.ext.WriteHandlerFactory.ResponseType;

/**
 * Response a file to client.
 * 
 * @author idoldefine
 * @since 2016/07/15
 *
 */
@Component
public class FileRequestDispatch extends HttpRequestDispatch {
	private static final Logger logger = LoggerFactory
			.getLogger(FileRequestDispatch.class);
	@Config
	private String fileDir = FileRequestDispatch.class.getResource("/")
			.getPath();

	@Override
	public void doRequest(XServerHttpContextAttachment attachment,WriteHandler writeHandler)
			throws Exception {
		String path = attachment.getRequest().getPath();
		logger.debug("request file[{}] from server", path);

		@SuppressWarnings("resource")
		RandomAccessFile file = new RandomAccessFile(fileDir + "/" + path, "r");
	     new DefaultFileRegion(file.getChannel(), 0, file.length());
	}

	@Override
	public Object wrapResponse(XServerHttpContextAttachment attachment,
			Object result) {
		String path = attachment.getRequest().getPath();

		path = removeSeparator(path);
		fileDir = removeSeparator(fileDir);

		String filePath = fileDir + "/" + path;

		XServerHttpResponse response = attachment.getResponse();

		MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
		response.headers().set(HttpEnum.Header.CONTENT_TYPE.getName(),
				mimeTypesMap.getContentType(filePath));

		return result;
	}

	@Override
	public ResponseType getResponsePrototype(
			XServerHttpContextAttachment attachment) {
		return ResponseType.HTTP;
	}

	@Override
	public boolean accept(XServerHttpContextAttachment attachment) {
		String path = attachment.getRequest().getPath();

		if (path.contains(".")) {
			return true;
		}

		return false;
	}

	private String removeSeparator(String path) {
		if (path != null && path.endsWith("/")) {
			path = path.substring(0, path.length() - 1);
		}
		return path;
	}
}
